﻿using System;
using System.Collections;
using System.Diagnostics;
using System.ComponentModel;

using Jayrock.Json;
using jr = Jayrock.Json.Conversion;
using Jayrock.Json.Conversion.Converters;

namespace N2.Jayrock.Json.Converters
{
	using ComponentModel;

	public class ContentItemLinkExporter : jr.IObjectMemberExporter
	{
		#region Fields

		readonly PropertyDescriptor Property;

		#endregion Fields

		#region ctor
		public ContentItemLinkExporter(PropertyDescriptor property)
		{
			this.Property = property;
		}
		#endregion ctor

		#region Methods

		public void Export(
				jr.ExportContext context,
				global::Jayrock.Json.JsonWriter writer,
				object source)
		{
			if (context == null) throw new ArgumentNullException("context");
			if (writer == null) throw new ArgumentNullException("writer");
			if (source == null) throw new ArgumentNullException("source");

			var _item = source as ContentItem;

			if (null == _item)
				return;

			var _value = this.Property.GetValue(_item) as ContentItem;

			writer.WriteMember(Property.Name);
			if (null == _value) {
				writer.WriteNull();
			} else {
				context.Export(new {
					__deferred = new {
						_value.ID,
					}
				}, writer);
			}
		}

		#endregion Methods
	}
}